package cn.janescott.inner.space.lib.boot.starter;

import cn.janescott.inner.space.lib.boot.properties.ThymeleafProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import java.util.Map;

/**
 * 设置thymeleaf全局参数
 * @date 2018/7/20
 * @author scott
 */
@Configuration
@ConditionalOnWebApplication
@ConditionalOnProperty(prefix = "me.thymeleaf", name = "enabled", havingValue = "true")
@EnableConfigurationProperties({ThymeleafProperties.class})
@ConditionalOnBean({ThymeleafViewResolver.class})
@AutoConfigureAfter(ThymeleafAutoConfiguration.class)
public class ThymeleafGlobalSettingsAutoConfiguration implements InitializingBean {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private ThymeleafProperties properties;

    @Autowired
    public void setProperties(ThymeleafProperties properties) {
        this.properties = properties;
    }

    private ThymeleafViewResolver resolver;

    @Autowired
    public void setResolver(ThymeleafViewResolver resolver) {
        this.resolver = resolver;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, String> params = properties.getParams();
        if (!CollectionUtils.isEmpty(params) && logger.isInfoEnabled()) {
            for (Map.Entry<String, String> next : params.entrySet()) {
                logger.info(next.getKey() + ":" + next.getValue());
            }
        }
        resolver.setStaticVariables(params);
    }
}
